Variadic function
tip
man 3 stdarg
Declaration
To declare a function with a variable number of arguments, use the ...
notation:
#include <stdarg.h>
void my_function(int n, ...);
stdarg.h
declares a type va_list
and defines three macros for
stepping through a list of arguments.
va_start
void va_start(va_list ap, last);
It initializes the va_list ap
. last
is the last argument of which
the calling function knows the type.
va_end
void va_end(va_list ap);
This must be called after va_start()
and your treatment.
va_arg
type va_arg(va_list ap, type);
Each call to va_arg()
modifies ap
so that the next call returns the
next argument.
The argument will have the same type as the given type
.
Number of arguments
- It is not possible to know how many arguments have been passed to the function.
- If
va_arg
is called after the last argument, this will lead to an undefined behavior.
Example
#include <stdarg.h>
#include <stdio.h>
void print_unsigned(int nb, ...)
{
unsigned int i;
va_list ap;
va_start(ap, nb); // Initialization.
for (int n = 0; n < nb; ++n)
{
i = va_arg(ap, unsigned); // Get an unsigned int.
printf("%u ", i);
}
va_end(ap); // Set ap to undefine.
}
int main(void)
{
print_unsigned(4, 1, 2, 3, 4);
putchar('\n');
print_unsigned(6, -1, 2, 3, 4, 5, 6);
return 0;
}